//go:build windows

package gui

import (
	_ "embed"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"sync"
	"time"
)

//go:embed create_workflow_form.ps1
var createWorkflowScript string

//go:embed wpf/MainWindow.xaml
var mainWindowXAML string

//go:embed wpf/MainWindow.ps1
var mainWindowScript string

// Manager manages GUI windows using PowerShell
type Manager struct {
	mu     sync.Mutex
	active bool
}

// NewManager creates a new GUI manager
func NewManager() *Manager {
	return &Manager{}
}

// WorkflowRequest represents a workflow creation request
type WorkflowRequest struct {
	Summary    string
	Motivation string
	Timeout    time.Duration
}

// WorkflowResult represents the result of workflow creation
type WorkflowResult struct {
	ChangeID   string `json:"change_id"`
	Complexity string `json:"complexity"`
	Cancelled  bool   `json:"cancelled"`
	Error      string `json:"error"`
}

// ShowCreateWorkflowForm shows the create workflow form using PowerShell
func (m *Manager) ShowCreateWorkflowForm(req WorkflowRequest) (*WorkflowResult, error) {
	m.mu.Lock()
	if m.active {
		m.mu.Unlock()
		return nil, errors.New("another window is already active")
	}
	m.active = true
	m.mu.Unlock()

	defer func() {
		m.mu.Lock()
		m.active = false
		m.mu.Unlock()
	}()

	// Write embedded script to temporary file
	tmpFile := filepath.Join(os.TempDir(), "workflow_create_form.ps1")
	if err := os.WriteFile(tmpFile, []byte(createWorkflowScript), 0644); err != nil {
		return nil, fmt.Errorf("failed to write temporary script: %w", err)
	}
	defer os.Remove(tmpFile)

	// Prepare PowerShell command
	args := []string{
		"-ExecutionPolicy", "Bypass",
		"-NoProfile",
		"-File", tmpFile,
		"-Summary", req.Summary,
		"-Motivation", req.Motivation,
		"-TimeoutSeconds", fmt.Sprintf("%d", int(req.Timeout.Seconds())),
	}

	// Execute PowerShell script
	cmd := exec.Command("powershell.exe", args...)
	output, err := cmd.Output()
	if err != nil {
		return nil, fmt.Errorf("failed to execute PowerShell script: %w", err)
	}

	// Parse JSON result
	var result WorkflowResult
	if err := json.Unmarshal(output, &result); err != nil {
		return nil, fmt.Errorf("failed to parse result: %w", err)
	}

	return &result, nil
}

// generateChangeID generates a change ID from summary
func generateChangeID(summary string) string {
	timestamp := time.Now().Format("20060102-150405")
	return fmt.Sprintf("WF-%s", timestamp)
}

// detectComplexity detects complexity based on motivation length
func detectComplexity(motivation string) string {
	length := len(motivation)
	if length > 500 {
		return "complex"
	} else if length > 200 {
		return "medium"
	}
	return "simple"
}

// ShowMainWindow shows the WPF main window
func (m *Manager) ShowMainWindow() error {
	m.mu.Lock()
	if m.active {
		m.mu.Unlock()
		return errors.New("another window is already active")
	}
	m.active = true
	m.mu.Unlock()

	defer func() {
		m.mu.Lock()
		m.active = false
		m.mu.Unlock()
	}()

	// Create temporary directory for WPF files
	tmpDir := filepath.Join(os.TempDir(), "workflow-wpf")
	if err := os.MkdirAll(tmpDir, 0755); err != nil {
		return fmt.Errorf("failed to create temp directory: %w", err)
	}

	// Write XAML file
	xamlPath := filepath.Join(tmpDir, "MainWindow.xaml")
	if err := os.WriteFile(xamlPath, []byte(mainWindowXAML), 0644); err != nil {
		return fmt.Errorf("failed to write XAML file: %w", err)
	}

	// Write PowerShell script
	scriptPath := filepath.Join(tmpDir, "MainWindow.ps1")
	if err := os.WriteFile(scriptPath, []byte(mainWindowScript), 0644); err != nil {
		return fmt.Errorf("failed to write PowerShell script: %w", err)
	}

	// Execute PowerShell script
	cmd := exec.Command("powershell.exe",
		"-ExecutionPolicy", "Bypass",
		"-NoProfile",
		"-File", scriptPath,
	)

	// Run and wait
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("failed to execute WPF window: %w", err)
	}

	return nil
}
